import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_chat/config/app_config.dart';
import 'package:get_it/get_it.dart';
import 'package:dio/dio.dart';
import 'dart:ui';
import 'package:oktoast/oktoast.dart';
import 'package:async/src/async_memoizer.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_chat/config/antd_icons.dart';
import 'package:flutter_chat/page/mine_page.dart';
import 'package:flutter_chat/page/mession_page.dart';
import 'package:flutter_chat/page/goods_page.dart';
import 'package:flutter_chat/page/chat_page.dart';
import 'package:flutter_chat/page/full_screen_scanner_page.dart';

class HomePage extends StatefulWidget {
//  final String token;
//  final int fromUserId;
//  final String userName;

//  const HomePage(data,
//      {Key key, this.token, this.fromUserId, this.userName})
//      : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  AppConfig appConfig;
  var _pageTitle = ['会话', '通讯录', '我的'];
  int _selectedIndex = 0;
  List<Widget> _pages;
  PageController _controller;

  // 缓存子页面
  final AsyncMemoizer _memoizer = AsyncMemoizer();

//  _fetchMessionList(){
//    return _memoizer.runOnce(() async {
//      List<Mession> messionList = List<Mession>();
//      try {
//        final response =
//        await Dio().get('${Config.BASE_URL}/mession/get_messions');
//        if (response.statusCode == 200) {
//          messionList = Mession.fromJson(response.toString());
//        }
//        return messionList;
//      } catch (e) {
//        print('MessionPage->' + e.toString());
//      }
//      return messionList;
//    });
//  }

  @override
  void initState() {
    super.initState();
    appConfig = GetIt.instance<AppConfig>();
    _pages = List()
      ..add(ChatPage())
      ..add(MessionPage())
      ..add(MinePage())
      ..add(GoodsPage());
    _controller = PageController(initialPage: _selectedIndex);
  }

//  final String text;
//  final Color backgroundColor;
//  @override
//  void initState() {
//    showToast("连接服务器成功");
//  }

//  _DartTokenPageState(this.text, this.backgroundColor);
  @override
  // ignore: must_call_super
  Widget build(BuildContext context) {
    print(appConfig);
    print(appConfig.isBigScreen);

    Widget _bulidBody(BuildContext context) {
      return PageView.builder(
          physics: NeverScrollableScrollPhysics(), //viewPage禁止左右滑动
          controller: _controller,
          itemCount: _pages.length,
          itemBuilder: (context, index) => _pages[index]);
    }

    // ignore: non_constant_identifier_names
    Widget _AppBar(BuildContext context) {
      return new AppBar(
          title: Text(_pageTitle[_selectedIndex]),
          actions: <Widget>[
            PopupMenuButton(
              icon: Icon(AntdIcons.icon_roundadd),
              itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
                PopupMenuItem<String>(
                  child: Row(
                      crossAxisAlignment: CrossAxisAlignment.baseline,
                      textBaseline: TextBaseline.alphabetic,
                      children: <Widget>[
                        Icon(AntdIcons.weChatFill, color: Colors.black),
                        Spacer(
                          flex: 1,
                        ),
                        Text("发起群聊"),
                        Spacer(
                          flex: 3,
                        ),
                      ]),
                  value: "1",
                ),
                PopupMenuItem<String>(
                  child: Row(
                      crossAxisAlignment: CrossAxisAlignment.baseline,
                      textBaseline: TextBaseline.alphabetic,
                      children: <Widget>[
                        Icon(AntdIcons.icon_addperson, color: Colors.black),
                        Spacer(
                          flex: 1,
                        ),
                        Text("添加好友"),
                        Spacer(
                          flex: 3,
                        ),
                      ]),
                  value: "2",
                ),
                PopupMenuItem<String>(
                  child: Row(
                      crossAxisAlignment: CrossAxisAlignment.baseline,
                      textBaseline: TextBaseline.alphabetic,
                      children: <Widget>[
                        Icon(AntdIcons.icon_scan, color: Colors.black),
                        Spacer(
                          flex: 1,
                        ),
                        Text("扫一扫"),
                        Spacer(
                          flex: 3,
                        ),
                      ]),
                  value: "3",
                ),
                PopupMenuItem<String>(
                  child: Row(
                      crossAxisAlignment: CrossAxisAlignment.baseline,
                      textBaseline: TextBaseline.alphabetic,
                      children: <Widget>[
                        Icon(AntdIcons.icon_gather_fill, color: Colors.black),
                        Spacer(
                          flex: 1,
                        ),
                        Text("收付款"),
                        Spacer(
                          flex: 3,
                        ),
                      ]),
                  value: "4",
                ),
              ],
              onSelected: (String action) async {
                switch (action) {
                  case "1":
                    print("发起群聊");
                    break;
                  case "2":
                    print("添加好友");
                    break;
                  case "3":
                    print("扫一扫");

                    try {
                      Navigator.push(context,
                          new MaterialPageRoute(builder: (context) {
                        return FullScreenScannerPage();
                      }));
//                  print(_permissionStatusCamera);
//                  print(_scannerController);
//                  _scannerController.startCamera();
                    } catch (e) {
                      print(e);
                    }

//                var result = await BarcodeScanner.scan();
//                print(result
//                    .type); // The result type (barcode, cancelled, failed)
//                print(result.rawContent); // The barcode content
//                print(result.format); // The barcode format (as enum)
//                print(result
//                    .formatNote); // If a unknown format was scanned this field contains a note
                    break;
                  case "4":
                    print("收付款");
                    break;
                }
              },
              onCanceled: () {
                print("onCanceled");
              },
            )
          ]);
    }

    // ignore: non_constant_identifier_names
    Widget _BottomNavigationBar(BuildContext context) {
      return new BottomNavigationBar(
        // 底部导航
        items: <BottomNavigationBarItem>[
          BottomNavigationBarItem(
              icon: Icon(AntdIcons.weChatFill), title: Text('会话')),
          BottomNavigationBarItem(
              icon: Icon(AntdIcons.iconAddressBookFil), title: Text('通讯录')),
          BottomNavigationBarItem(
              icon: Icon(AntdIcons.iconSignal), title: Text('我')),
        ],
        currentIndex: _selectedIndex,
        fixedColor: Colors.blue,
        onTap: _onItemTapped,
      );
    }

    return Scaffold(
      appBar: appConfig.isBigScreen ? null : _AppBar(context),
      body: _bulidBody(context),
      bottomNavigationBar:
          appConfig.isBigScreen ? null : _BottomNavigationBar(context),
//        body: SafeArea(
//          child: Column(mainAxisSize: MainAxisSize.max, children: <Widget>[
//            Text(" hello world "),
//            Text(" I am Jack "),
//            Column(
//              mainAxisAlignment: MainAxisAlignment.center,
//              children: <Widget>[
//                Text(" hello world "),
//                Text(" I am Jack "),
//                RaisedButton(
//                  onPressed: _incrementCounter,
//                  child: Text('Increment Counter 桌面'),
//                ),
//                RaisedButton(
//                  onPressed: _incrementCounterPrint,
//                  child: Text('Increment Counter'),
//                ),
//              ],
//            ),
//          ]),
//        )
    );
  }

  _incrementCounter() async {
    print(widget);
    SharedPreferences prefs = await SharedPreferences.getInstance();
    int counter = (prefs.getInt('counter') ?? 0) + 1;
    print('Pressed $counter times.');
    await prefs.setInt('counter', counter);
  }

  _incrementCounterPrint() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    int counter = prefs.getInt('counter');
    print(counter);
  }

  void _onItemTapped(int index) {
    print(_controller);
    _controller.jumpToPage(index);
    print(index);
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  bool get wantKeepAlive => true;
}
